package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"wx-api/adx-api/handlers"
	"wx-api/adx-api/middleware"
	"wx-api/adx-api/routers"
	"wx-api/adx-api/services/se_user"
)

func RouteApi(m string) *gin.Engine {
	var r *gin.Engine
	//if m == "product" {
	//	r = gin.New()
	//} else {
	//	gin.SetMode("debug")
	//	r = gin.Default()
	//}
	gin.SetMode("debug")
	r = gin.Default()
	r.Use(cors())

	//负载探活
	r.Any("/", Rz)
	Api := r.Group("/api/v1/")
	//登录
	Api.POST("login", func(c *gin.Context) {
		se_user.Login(handlers.NewBaseController(c))
	})
	Api.POST("login_out", func(c *gin.Context) {
		se_user.LoginOut(handlers.NewBaseController(c))
	})
	app_api := Api.Group("/")
	app_api.Use(middleware.CheckAdxLogin())
	//获取账户详情
	app_api.GET("uinfo", func(c *gin.Context) {
		se_user.GetUserInfo(handlers.NewBaseController(c))
	})
	routers.Route_SspList(app_api)
	routers.Route_SspApp(app_api)
	routers.Route_SspSlot(app_api)
	routers.Route_SspTemplate(app_api)
	routers.Route_AdxPlan(app_api)
	//预算相关
	routers.Route_ChannelList(app_api)
	//预算模版
	routers.Route_ChannelTemplate(app_api)
	//广告源相关
	routers.Route_ChannelSlot(app_api)
	//渠道相关
	routers.Route_AdxList(app_api)
	//adx模版
	routers.Route_AdxTemplate(app_api)
	//应用相关
	routers.Route_AdxApp(app_api)
	//广告位相关
	routers.Route_AdxSlot(app_api)
	//报表相关
	routers.Route_Report(app_api)

	return r
}

func cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("Origin")
		c.Header("Access-Control-Allow-Origin", origin) // 这是允许访问所有域
		c.Header("Access-Control-Allow-Methods", "*")   //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
		//header的类型
		c.Header("Access-Control-Request-Headers", "*")
		c.Header("Access-Control-Allow-Headers", "*")
		//允许跨域设置                                                                                                      可以返回其他子段
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Content-Type,token") // 跨域关键设置 让浏览器可以解析
		//c.Header("Access-Control-Max-Age", "172800")        // 缓存请求信息 单位为秒
		c.Header("Access-Control-Allow-Credentials", "true")
		//c.Set("content-type", "application/json") // 设置返回格式是json
		//fmt.Println(c.Request.RequestURI)
		//fmt.Println(c.Request.Method)

		//拦截所有options请求
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(200)
			return
		}

		c.Next()
		return

	}
}

func Rz(c *gin.Context) {
	str := make(map[string]string)
	str["msg"] = "success"
	c.JSON(http.StatusOK, str)
	return
}
